from django.shortcuts import render
from rest_framework import viewsets, permissions
from rest_framework.decorators import action
from rest_framework.response import Response
from django.db.models import Count
from .models import Category, Product
from .serializers import CategorySerializer, ProductSerializer
from users.permissions import PurchaserPermission, SalesmanPermission, DeliverymanPermission, CustomerPermission, IsAdmin
from rest_framework.views import APIView
  
  # Create your views here.

class CategoryViewSet(viewsets.ModelViewSet):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_permissions(self):
        if self.action in ['create', 'update', 'partial_update', 'destroy']:
            return [PurchaserPermission()|SalesmanPermission()|IsAdmin()]
        return [permissions.IsAuthenticated()]

    @action(detail=False, methods=['get'])
    def statistics(self, request):
        """获取各类别的产品数量统计"""
        stats = Category.objects.annotate(
            product_count=Count('products')
        ).values('id', 'name', 'product_count')
        return Response(stats)

class ProductViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_permissions(self):
        return [permissions.IsAuthenticated()]

    def get_queryset(self):
        queryset = Product.objects.all()
        category = self.request.query_params.get('category', None)
        supplier = self.request.query_params.get('supplier', None)
        
        if category:
            queryset = queryset.filter(category_id=category)
        if supplier:
            queryset = queryset.filter(supplier_id=supplier)
            
        return queryset

    @action(detail=False, methods=['get'])
    def low_stock(self, request):
        """获取库存预警的产品"""
        from warehouse.models import Inventory
        from django.db.models import Sum
        
        products = Product.objects.annotate(
            total_stock=Sum('inventories__quantity')
        ).filter(total_stock__lte=10)  # 假设库存小于等于10为预警
        
        return Response(ProductSerializer(products, many=True).data)
 
 
class ProductListView(APIView):
     permission_classes = [PurchaserPermission]
 
class ProductDetailView(APIView):
     permission_classes = [SalesmanPermission]
